// @ts-nocheck
import amapFile from '@/libs/amap-wx.130.js';
import { AMAP_KEY } from '../config/map';

/**
 * 高德地图微信小程序工具类
 */

let amapInstance: any = null;

// 初始化高德地图实例
export function initAmap() {
  if (!amapInstance) {
    amapInstance = new amapFile.AMapWX({
      key: AMAP_KEY
    });
  }
  return amapInstance;
}

/**
 * 获取当前定位
 */
export function getCurrentLocation(): Promise<any> {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02',
      success: (res) => {
        resolve({
          latitude: res.latitude,
          longitude: res.longitude
        });
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

/**
 * 逆地理编码 - 根据经纬度获取地址
 */
export function getRegeo(location: { latitude: number; longitude: number }): Promise<any> {
  return new Promise((resolve, reject) => {
    const amap = initAmap();
    
    amap.getRegeo({
      location: `${location.longitude},${location.latitude}`,
      success: (data: any) => {
        if (data && data.length > 0) {
          const regeocode = data[0];
          resolve({
            success: true,
            province: regeocode.regeocodeData.addressComponent.province,
            city: regeocode.regeocodeData.addressComponent.city || regeocode.regeocodeData.addressComponent.province,
            district: regeocode.regeocodeData.addressComponent.district,
            township: regeocode.regeocodeData.addressComponent.township,
            street: regeocode.regeocodeData.addressComponent.streetNumber.street,
            streetNumber: regeocode.regeocodeData.addressComponent.streetNumber.number,
            fullAddress: regeocode.regeocodeData.formatted_address,
            addressComponent: regeocode.regeocodeData.addressComponent,
            pois: regeocode.regeocodeData.pois || []
          });
        } else {
          reject({
            success: false,
            message: '获取地址失败'
          });
        }
      },
      fail: (error: any) => {
        console.error('逆地理编码失败:', error);
        reject({
          success: false,
          message: error.errMsg || '获取地址失败'
        });
      }
    });
  });
}

/**
 * 地理编码 - 根据地址获取经纬度
 */
export function getGeo(address: string, city?: string): Promise<any> {
  return new Promise((resolve, reject) => {
    const amap = initAmap();
    
    amap.getGeo({
      address: address,
      city: city || '',
      success: (data: any) => {
        if (data && data.length > 0) {
          const geocode = data[0];
          resolve({
            success: true,
            longitude: geocode.longitude,
            latitude: geocode.latitude,
            formattedAddress: geocode.name
          });
        } else {
          reject({
            success: false,
            message: '地址解析失败'
          });
        }
      },
      fail: (error: any) => {
        console.error('地理编码失败:', error);
        reject({
          success: false,
          message: error.errMsg || '地址解析失败'
        });
      }
    });
  });
}

/**
 * 输入提示 - 搜索地址
 */
export function getInputtips(keywords: string, city?: string): Promise<any> {
  return new Promise((resolve, reject) => {
    const amap = initAmap();
    
    amap.getInputtips({
      keywords: keywords,
      city: city || '',
      success: (data: any) => {
        if (data && data.tips) {
          resolve({
            success: true,
            tips: data.tips.map((tip: any) => ({
              name: tip.name,
              address: tip.address,
              district: tip.district,
              location: tip.location
            }))
          });
        } else {
          resolve({
            success: true,
            tips: []
          });
        }
      },
      fail: (error: any) => {
        console.error('地址搜索失败:', error);
        reject({
          success: false,
          tips: []
        });
      }
    });
  });
}

/**
 * 路径规划 - 计算两点距离和路线
 */
export function getDrivingRoute(origin: string, destination: string): Promise<any> {
  return new Promise((resolve, reject) => {
    const amap = initAmap();
    
    amap.getDrivingRoute({
      origin: origin,
      destination: destination,
      success: (data: any) => {
        if (data && data.paths && data.paths.length > 0) {
          const path = data.paths[0];
          resolve({
            success: true,
            distance: path.distance, // 距离(米)
            duration: path.duration, // 时间(秒)
            steps: path.steps
          });
        } else {
          reject({
            success: false,
            message: '路径规划失败'
          });
        }
      },
      fail: (error: any) => {
        console.error('路径规划失败:', error);
        reject({
          success: false,
          message: error.errMsg || '路径规划失败'
        });
      }
    });
  });
}

/**
 * 计算两点之间的直线距离(米)
 */
export function calculateDistance(
  lat1: number,
  lon1: number,
  lat2: number,
  lon2: number
): number {
  const R = 6371000; // 地球半径(米)
  const dLat = ((lat2 - lat1) * Math.PI) / 180;
  const dLon = ((lon2 - lon1) * Math.PI) / 180;

  const a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos((lat1 * Math.PI) / 180) *
      Math.cos((lat2 * Math.PI) / 180) *
      Math.sin(dLon / 2) *
      Math.sin(dLon / 2);

  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c;

  return Math.round(distance);
}

/**
 * 格式化距离显示
 */
export function formatDistance(distance: number): string {
  if (distance < 1000) {
    return `${distance}m`;
  } else {
    return `${(distance / 1000).toFixed(1)}km`;
  }
}